package com.zbbt.sportslottery.app;

import java.io.File;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.Builder;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;

import com.google.gson.JsonObject;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.zbbt.sportslottery.R;
import com.zbbt.sportslottery.bean.DialogBean.OnDialogClickListener;
import com.zbbt.sportslottery.bean.VersionInfo;
import com.zbbt.sportslottery.net.TypeGsonHttpHandler;
import com.zbbt.sportslottery.net.ZbHttpClient;
import com.zbbt.sportslottery.ui.activity.MainActivity;
import com.zbbt.sportslottery.ui.widget.SimpleCustomDialog;
import com.zbbt.sportslottery.util.AppUtil;
import com.zbbt.sportslottery.util.DialogUtil;
import com.zbbt.sportslottery.util.FileUtil;
import com.zbbt.sportslottery.util.LogUtil;
import com.zbbt.sportslottery.util.ToastUtil;

/**
 * 
 * @ClassName: UpdateVersion
 * @Description: 版本更新
 * @author：LiZhimin
 * @备注：
 * @version V1.0
 */
public class UpdateVersion {

	private static final String TAG = "UpdateVersion";

	public static final int PAGE_SPLASH = 0;// 来自启动页面

	public static final int PAGE_MAIN = 1;// 来自主页面

	public static final int PAGE_SETTING = 2;// 来自设置页面

	public static final String SER_VERSION_INFO = "update.obj";// 本地保存的序列化对象文件名

	private String APK_PATH = App.ROOT_PATH + Constant.APP_TAG + "_update.apk";

	private String appName = "";

	private Context context;

	public UpdateVersion(Context context) {
		this.context = context;
		appName = context.getResources().getString(R.string.app_name);
	}

	/**
	 * 
	 * @MethodName:RequestUpdateData
	 * @Description: 请求版本更新数据
	 * @author：LiZhimin
	 * @date：2014-3-19 下午6:06:20 void
	 */
	public void requestUpdateData(final int fromPage) {
		JsonObject jsonObject = new JsonObject();
		jsonObject.addProperty("appType", "2");
		ZbHttpClient.postNewApi(ServerConfig.API_UPDATE, jsonObject, new TypeGsonHttpHandler<VersionInfo>() {

			@Override
			public void onSuccess(VersionInfo data) {
				if (data != null) {
					// 1.保存更新信息到文件
					LogUtil.printI(TAG, "保存更新信息到本地");
					FileUtil.saveObject2File(data, SER_VERSION_INFO);
					// 2.设置页面请求后弹出版本更新
					if (fromPage == PAGE_SETTING) {
						checkUpdate(fromPage);
					}
				} else {
					LogUtil.printI(TAG, "data为空更新失败");
					if (fromPage == PAGE_SETTING) {
						ToastUtil.showShort("当前已是最新版本");
					}
				}
			}

			@Override
			public void onFailure(String errorCode, String errorMsg) {
				ToastUtil.showShort(errorMsg);
			}
		});

	}

	/**
	 * 
	 * @MethodName:checkUpdate
	 * @Description: 检测更新
	 * @author：LiZhimin
	 */
	public void checkUpdate(final int fromPage) {
		final VersionInfo versionInfo = (VersionInfo) FileUtil.readObjectFromFile(SER_VERSION_INFO);
		if (versionInfo != null) {
			LogUtil.printI(TAG, "读取本地更新成功:" + versionInfo.toString());
			if (isNewVersion(versionInfo.getVersion(), AppUtil.getVersionName(context))) {
				if (versionInfo.getIsUpdate()==1) {
					LogUtil.printI(TAG, "强制更新");
					forceUpdate(versionInfo);
				} else {
					LogUtil.printI(TAG, "一般更新");
					customUpdate(versionInfo);
				}
			} else {
				LogUtil.printI(TAG, "无需更新");
				if (fromPage == PAGE_SETTING) {
					ToastUtil.showLong("当前已是最新版本");
				}

			}
		}
	}

	/**
	 * 
	 * @MethodName:ForceUpdate
	 * @Description: 强制更新
	 * @author：LiZhimin
	 * @date：2014-3-19 下午5:50:40
	 * @param versionInfo
	 *            void
	 */
	private void forceUpdate(final VersionInfo versionInfo) {
		SimpleCustomDialog showConfirmDialog = DialogUtil.showConfirmDialog(context, "版本过低,须更新后才可使用",
				Html.fromHtml(versionInfo.getUpdateDes()), "取消", "更新", new OnDialogClickListener() {

					@Override
					public boolean onClick(View v) {
						AppUtil.killProcess();
						return false;
					}
				}, new OnDialogClickListener() {

					@Override
					public boolean onClick(View v) {
						showDownLoadNotify(versionInfo);
						return false;
					}
				});
		showConfirmDialog.setCanceledOnTouchOutside(false);
	}

	/**
	 * 
	 * @MethodName:customUpdate
	 * @Description: 常规更新
	 * @author：LiZhimin
	 * @date：2014-3-24 下午2:12:55
	 * @param versionInfo
	 *            void
	 */
	private void customUpdate(final VersionInfo versionInfo) {
		DialogUtil.showConfirmDialog(context, "发现新版本，请更新", Html.fromHtml(versionInfo.getUpdateDes()), "暂不升级",
				"立刻升级", null, new OnDialogClickListener() {

					@Override
					public boolean onClick(View v) {
						showDownLoadNotify(versionInfo);
						return false;
					}
				});
	}

	/**
	 * 
	 * @MethodName:showDownLoadNotify
	 * @Description: 弹出下载通知
	 * @author：LiZhimin
	 * @date：2014-3-24 下午2:43:58
	 * @param versionInfo
	 * @param dialog
	 *            void
	 */
	private void showDownLoadNotify(final VersionInfo versionInfo) {
		String apkFileName = AppUtil.getApkFileName(context, APK_PATH);
		if (!TextUtils.isEmpty(apkFileName) && apkFileName.equals(versionInfo.getVersion())) {
			installApk(APK_PATH);
		} else {
			ToastUtil.showLong("开始更新...");
			final NotificationManager mNotifyManager = (NotificationManager) context
					.getSystemService(Context.NOTIFICATION_SERVICE);
			final Builder mBuilder = new NotificationCompat.Builder(context);
			mBuilder.setContentTitle(appName + "更新通知").setContentText("开始更新").setSmallIcon(R.drawable.icon)
					.setTicker(appName + "正在更新").setAutoCancel(true);
			Intent intent = new Intent(context, MainActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			PendingIntent pend = PendingIntent.getActivity(context, 0, intent,
					PendingIntent.FLAG_UPDATE_CURRENT);
			mBuilder.setContentIntent(pend);
			mNotifyManager.notify(0, mBuilder.build());

			ZbHttpClient.download(versionInfo.getUpdateUrl(), APK_PATH, new RequestCallBack<File>() {

				@Override
				public void onSuccess(ResponseInfo<File> responseInfo) {
					installApk(APK_PATH);
					PendingIntent pend = PendingIntent.getActivity(context, 0, getInstallApkIntent(APK_PATH),
							PendingIntent.FLAG_UPDATE_CURRENT);
					mBuilder.setContentIntent(pend);
					mNotifyManager.notify(0, mBuilder.build());
				}

				@Override
				public void onFailure(HttpException error, String msg) {
					mBuilder.setContentText("下载失败,请稍后重试").setProgress(0, 0, false);
					mNotifyManager.notify(0, mBuilder.build());
				}

				@Override
				public void onLoading(long total, long current, boolean isUploading) {
					if (current <= total) {
						int percent = (int) (((float) current / total) * 100);
						if (percent != 100) {
							mBuilder.setProgress(100, percent, false);
							mBuilder.setContentText("更新进度" + percent + "%");
							mNotifyManager.notify(0, mBuilder.build());
						} else if (percent == 100) {
							mBuilder.setContentText("下载完成").setProgress(0, 0, false);
							mNotifyManager.notify(0, mBuilder.build());
						}
					}
					super.onLoading(total, current, isUploading);
				}
			});

		}
	}

	public static boolean isNewVersion(String newVersion, String oldVersion) {
		LogUtil.printI(TAG, "oldVersion = " + oldVersion);
		LogUtil.printI(TAG, "newVersion = " + newVersion);

		if (TextUtils.isEmpty(newVersion) || TextUtils.isEmpty(oldVersion)) {
			return false;
		}
		String newNum = newVersion.replace(".", "");
		String oldNum = oldVersion.replace(".", "");
		try {
			return Integer.parseInt(newNum) > Integer.parseInt(oldNum);
		} catch (NumberFormatException e) {
			e.printStackTrace();
			return false;
		}
	}

	public Intent getInstallApkIntent(String filePath) {
		LogUtil.printI(TAG, filePath);
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		i.setDataAndType(Uri.parse("file://" + filePath), "application/vnd.android.package-archive");
		return i;
	}

	public void installApk(String filePath) {
		context.startActivity(getInstallApkIntent(filePath));
	}

}
